package com.apes.pi.parser;

import com.apes.framework.api.ApesParser;
import com.apes.framework.plugin.esb.parser.node.ChainNodeParser;
import com.apes.framework.plugin.esb.processor.ChainProcessor;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.plugin.filereader.xml.ApesXmlParser;
import com.apes.framework.plugin.filereader.xml.SimpleApesElement;
import com.apes.pi.model.Pipe;
import org.springframework.stereotype.Component;

/**
 * 功能：Pipe解析器
 *
 * @author xul
 * @create 2019-11-05 9:37
 */
@Component
public class PipeParser implements ApesParser<PipeContext, ChainProcessor> {

    @Override
    public ChainProcessor parse(PipeContext context) {
        Pipe pipe = context.getPipe();
        String elementName = pipe.getPattern().getCode();
        ApesParser parser = getApesElementParser(elementName);
        if(parser == null) throw new RuntimeException(String.format("管道模式:%s 未实现！", pipe.getPattern().getCode()));
        ApesElement element = new SimpleApesElement();
        element.setName(elementName);
        element.setParser(parser);
        element.getAttributes().putAll(context.getParams());
        pipe.getParams().stream().forEach(param -> element.setAttribute(param.getType().getCode(), param.getValue()));
        return element.parse();
    }

    public ApesParser getApesElementParser(String elementName) {
        String key = ApesXmlParser.getKey(ChainNodeParser.domain, elementName);
        return ApesXmlParser.getApesElementParser(key);
    }
}
